﻿
function getDocumentWidth(doc) {
    var documentElementWidth = 0;
    if (!isNullOrUndefined(doc.documentElement) && !isNullOrUndefined(doc.documentElement.scrollWidth) && !isNullOrUndefined(doc.documentElement.offsetWidth)) {
        documentElementWidth = Math.max(doc.documentElement.scrollWidth, doc.documentElement.offsetWidth);
    }
    return Math.max(doc.body.scrollWidth, doc.body.offsetWidth, documentElementWidth);
}
function getDocumentHeight(doc) {
    var documentElementHeight = 0;
    if (!isNullOrUndefined(doc.documentElement) && !isNullOrUndefined(doc.documentElement.scrollHeight) && !isNullOrUndefined(doc.documentElement.offsetHeight)) {
        documentElementHeight = Math.max(doc.documentElement.scrollHeight, doc.documentElement.offsetHeight);
    }
    return Math.max(doc.body.scrollHeight, doc.body.offsetHeight, documentElementHeight);
}
function isNullOrUndefined(obj) {
    return typeof (obj) == 'undefined' || obj == null;
}
function closeWin(formWin) {
    var parts = formWin.location.search.substr(1).split('&');
    for (var i = 0; i < parts.length; i++) {
        if (parts[i].indexOf('Source=') == 0) {
            formWin.location = decodeURIComponent(parts[i].substr(7));
            return;
        }
    }
    formWin.close();
}
function InfoJetCustom_CloseWindow(formWin) {
    closeWin(formWin);
}



function isMobileBrowser() {
    u = navigator.userAgent;
    if (!!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/)) {
        return true;
    }
    else {
        return false;
    }
}

function InfoBus_Submit() {
    window.frames["container"].InfoJet_DefaultSubmit();
}
function GetCurrentView() {
    return getContentFrame().InfoBus_CurrentViewName;
}
function InfoBus_DoSwitchView(formViewId) {
    getContentFrame().InfoJet_DoSwitchView(formViewId);
}
function updateDDValue() {
    SP.Ribbon.PageManager.get_instance().get_commandDispatcher().executeCommand(Commands.CommandIds.ApplicationStateChanged, null);
}
function InfoBus_PrintPreview() {
    getContentFrame().InfoJet_OpenPrintableVersion(null);
}
function checkValidate() {
    if (!InfoJet_IsValid()) {
        alert(InfoJet_LocalResources["CorrectFirstMessage"]);
        return false;
    }
    return true;
}

function closeDlg_parent() {
    _overlay.parentNode.removeChild(_overlay);
    _overlay = null;
}
function closeDlg() {
    parent.closeDlg_parent();
    _overlay2.parentNode.removeChild(_overlay2);
    _overlay2 = null;
    var saveDiv = document.getElementById('saveDiv');
    saveDiv.style.display = 'none';
}


// for People Editor
var EntityEditor_UseContentEditableControl = true;
function CallbackWrapper_UserField(xml, pressButton) {
    if (xml == null)
        return;

    var ctx = $(InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(pressButton))))));
    EntityEditorCallback(xml, ctx);
}
function __Dialog__InfoBusUserField(event, pressButton, defaultSearch) {
    var tr = InfoJet_GetParent(InfoJet_GetParent(pressButton));
    var allowMultiple = tr.getAttribute("allowMultiple");
    var sharePointGroup = tr.getAttribute("sharePointGroup");
    if (sharePointGroup == '0')
        sharePointGroup = '';
    var searchPeopleOnly = tr.getAttribute("searchPeopleOnly");
    if (searchPeopleOnly == 'true')
        searchPeopleOnly = 'User%2CSecGroup';
    else
        searchPeopleOnly = 'User%2CSecGroup%2CSPGroup';
    var sDialogUrl = '\u002f_layouts\u002fPicker.aspx?MultiSelect=' + allowMultiple + '\u0026CustomProperty=' + searchPeopleOnly + '\u00253B' + sharePointGroup + '\u00253B15\u00253B\u00253B\u00253BFalse\u0026EntitySeparator=\u00253B\u0026DialogTitle=Select%20People%20and%20Groups\u0026DialogImage=\u00252F\u00255Flayouts\u00252Fimages\u00252Fppeople\u00252Egif\u0026PickerDialogType=Microsoft\u00252ESharePoint\u00252EWebControls\u00252EPeoplePickerDialog\u00252C\u002520Microsoft\u00252ESharePoint\u00252C\u002520Version\u00253D12\u00252E0\u00252E0\u00252E0\u00252C\u002520Culture\u00253Dneutral\u00252C\u002520PublicKeyToken\u00253D71e9bce111e9429c';
    sDialogUrl = sDialogUrl + '&DefaultSearch=' + defaultSearch;
    var sFeatures = 'resizable: yes; status: no; scroll: no; help: no; center: yes; dialogWidth : 575px; dialogHeight : 500px;';
    var rv = InfoBus_commonShowModalDialog(sDialogUrl, sFeatures, CallbackWrapper_UserField, pressButton);
}

function InfoBus_commonShowModalDialog(url, features, callback, pressButton, args) {

    var rv;
    if (browseris.safari125up) {
        var l = 500, k = 550, p = "yes";
        var b = "width=" + l + ",height=" + k;
        var e = window.open(url, "_blank", b + ",modal=yes,dialog=yes");
        e.dialogArguments = null;
        window.onfocus = function () {
            var a = document.getElementById("__spPickerHasReturnValue") != null && document.getElementById("__spPickerHasReturnValue").value == "1" || commonModalDialogReturnValue.isSet();
            if (e && !e.closed && !a) {
                e.focus();
            }
            else {
                window.onfocus = null;
                if (document.getElementById("__spPickerHasReturnValue") != null && document.getElementById("__spPickerHasReturnValue").value == "1" && document.getElementById("__spPickerReturnValueHolder") != null) {
                    rv = document.getElementById("__spPickerReturnValueHolder").value;
                } else if (commonModalDialogReturnValue.isSet()) {
                    rv = commonModalDialogReturnValue.get();
                }
            }
        };
        if (!browseris.ie)
            if (window.frameElement != null) {
                window.fndlgClose = InfoBus_HandleDialogReturnValue(rv, pressButton);
            }
}
if (window.showModalDialog && !browseris.safari125up) {
    rv = window.showModalDialog(url, args, features);
    if (typeof rv == "undefined" || rv == null) {
        if (document.getElementById("__spPickerHasReturnValue") != null && document.getElementById("__spPickerHasReturnValue").value == "1" && document.getElementById("__spPickerReturnValueHolder") != null) {
            rv = document.getElementById("__spPickerReturnValueHolder").value;
        } else if (commonModalDialogReturnValue.isSet()) {
            rv = commonModalDialogReturnValue.get();
        }

    }
    if (typeof rv == "undefined" || rv == null) {
        return;
    }
    InfoBus_HandleDialogReturnValue(rv, callback,pressButton);
}
}

function InfoBus_HandleDialogReturnValue(rv, callback, pressButton) {
    var xml = "<Principals>";
    //var jrv = rv.replace(/:/g, ""); jrv = jrv.replace(/\\/g, "\\\\");
    rv = "<xml>" + rv + "</xml>";
    var xmlDoc;
    if (window.ActiveXObject) {
        xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
        xmlDoc.async = false;
        xmlDoc.loadXML(rv);
    } else {
        rv = "<xml>" + rv + "</xml>";
        xmlDoc = new DOMParser().parseFromString(rv, "text/xml");
    }
    var jrv = jQuery(xmlDoc);
    jrv.find("Entity").each(function () {
        xml += "<Principal>";
        //            $(this).find("DictionaryEntry").each(function () {
        //                switch ($(this).find("Key").text()) {
        //                    case "PrincipalType":
        //                        xml += "<PrincipalType>" + $(this).find("Value").text() + "</PrincipalType>";
        //                        break;
        //                    default:
        //                        break;
        //                }
        //            });
        xml += "<PrincipalType>User</PrincipalType>";
        xml += "<DisplayName>" + $(this).attr("DisplayText") + "</DisplayName>";
        xml += "<AccountName>" + $(this).attr("Key") + "</AccountName>";
        xml += "</Principal>";
    });

    xml += "</Principals>";
    InfoBus_AddPrincipals(pressButton, xml);
    if (callback)
        callback(rv, pressButton);
}

function InfoBus_AddPrincipals(pngAddressButton, xml) {
    var tr = InfoJet_GetParent(InfoJet_GetParent(pngAddressButton));
    var pngId = tr.getAttribute("pngId");
    var allowMultiple = tr.getAttribute("allowMultiple");
    InfoJet_FocusItemIndex = -1;
    var box = InfoJet_GetElements(InfoJet_GetElements(tr)[0])[0];
    InfoJet_FocusControlId = box.id;
    var xdocForm = document.getElementById("xdoc_form");
    var xmlHtml = "<input type=hidden id=xdoc_param_png_added_xml name=xdoc_param_png_added_xml />";
    InfoJet_InsertAdjacentHTMLBeforeEnd(xdocForm, xmlHtml);
    document.getElementById("xdoc_param_png_added_xml").value = xml;
    var contextIdHtml = "<input type=hidden id=xdoc_param_png_context_id name=xdoc_param_png_context_id />";
    InfoJet_InsertAdjacentHTMLBeforeEnd(xdocForm, contextIdHtml);
    document.getElementById("xdoc_param_png_context_id").value = tr.id;
    var pngIdHtml = "<input type=hidden id=xdoc_param_png_id name=xdoc_param_png_id />";
    InfoJet_InsertAdjacentHTMLBeforeEnd(xdocForm, pngIdHtml);
    document.getElementById("xdoc_param_png_id").value = pngId;
    document.getElementById("xdoc_param_command").value = "Update_AddPrincipals";
    InfoJet_MoveProgress2ControlPosition(tr);
    InfoJet_Submit();
}
var busIsChange = "";

function InfoBus_KeyDownRw(upLevelDiv, e) {
    if (!e) e = window.event;
    var iKC = e.keyCode;
    if (iKC == 13) {
        canEvt(e);
        InfoBus_GetUpdatePrincipalsXml(upLevelDiv);
    }
}
function InfoBus_GetUpdatePrincipalsXml(upLevelDiv) {
    var userfieldId = upLevelDiv.id;
    userfieldId = userfieldId.replace("_upLevelDiv", "");
    if (!ValidatePickerControl(userfieldId)) {
        ShowValidationError();
        return false;
    }
    var tr = InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(InfoJet_GetParent(upLevelDiv))))));
    var divText = $(upLevelDiv).text();
    var arrUser = divText.split(';');
    var allowMultiple = tr.getAttribute("allowMultiple");
    var multierror = false;
    var multiempty = false;
        if (allowMultiple == 'false' && arrUser.length > 1) {
            if (arrUser.length == 2) {
                if (bus_Trim(arrUser[1]) != "") {
                    multierror = true;
                }
                else
                    multiempty = true;
            } else {
                multierror = true;
            }
        }
    if (multierror) {
        alert("Multiple selection is not allowed");
        return;
    }
//    if (multiempty)
//        return;
    //var arg = getUplevel(userfieldId);
    var ctx = userfieldId;
    EntityEditorSetWaitCursor(ctx);
    //_WebForm_DoCallback(userfieldId, arg, EntityEditorHandleCheckNameResult, ctx, EntityEditorHandleCheckNameError, true);

    if (bus_Trim(upLevelDiv.innerHTML) == busIsChange)
        return;

    var xml = "<Principals>";
    //    $(upLevelDiv).find("span>div").each(function () {
    //        if ($(this).attr("isresolved") == "True") {
    //            xml += "<Principal>";
    //            xml += "<DisplayName>" + $(this).attr("displaytext") + "</DisplayName>";
    //            xml += "<PrincipalType>User</PrincipalType>";
    //            xml += "<AccountName>" + $(this).attr("Key") + "</AccountName>";
    //            xml += "</Principal>";
    //            divText = divText.replace($(this).attr("displaytext"),"");
    //        }
    //    });
    $(upLevelDiv).empty();
    arrUser = divText.split(';');
    for (var i = 0; i < arrUser.length; i++) {
        if (bus_Trim(arrUser[i]) != "") {
            xml += "<Principal>";
            xml += arrUser[i];
            xml += "</Principal>";
        }
    }
    xml += "</Principals>";
    InfoBus_UpdatePrincipals(tr, xml);
}

function InfoBus_PrincipalChange(upLevelDiv) {
    busIsChange = bus_Trim(upLevelDiv.innerHTML);
}
function bus_Trim(str) {
    return str.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '');
}  
function InfoBus_UpdatePrincipals(pngTr, xml) {
    var tr = pngTr;
    var pngId = tr.getAttribute("pngId");
    var allowMultiple = tr.getAttribute("allowMultiple");
    InfoJet_FocusItemIndex = -1;
    var box = InfoJet_GetElements(InfoJet_GetElements(tr)[0])[0];
    InfoJet_FocusControlId = box.id;
    var xdocForm = document.getElementById("xdoc_form");
    var xmlHtml = "<input type=hidden id=xdoc_param_png_updated_xml name=xdoc_param_png_updated_xml />";
    InfoJet_InsertAdjacentHTMLBeforeEnd(xdocForm, xmlHtml);
    document.getElementById("xdoc_param_png_updated_xml").value = xml;
    var contextIdHtml = "<input type=hidden id=xdoc_param_png_context_id name=xdoc_param_png_context_id />";
    InfoJet_InsertAdjacentHTMLBeforeEnd(xdocForm, contextIdHtml);
    document.getElementById("xdoc_param_png_context_id").value = tr.id;
    var pngIdHtml = "<input type=hidden id=xdoc_param_png_id name=xdoc_param_png_id />";
    InfoJet_InsertAdjacentHTMLBeforeEnd(xdocForm, pngIdHtml);
    document.getElementById("xdoc_param_png_id").value = pngId;
    document.getElementById("xdoc_param_command").value = "Update_UpdatePrincipals";
    InfoJet_MoveProgress2ControlPosition(tr);
    InfoJet_Submit();
}

function InfoBus_ClickRw(d, c, a, b) {
    if (!a) a = window.event;
    if (browseris.ie) InfoBus_ClickRwIE(d, c, a, b);
    else InfoBus_ClickRwW3C(d, c, a, b);
}

function InfoBus_ClickRwW3C(t, s, r) {
    var f = null,
		c = null,
		i = null,
		b = null;
    var displayText = "";
    if (window.getSelection) {
        var k = window.getSelection();
        if (k != null) {
            c = k.focusNode.parentNode;
            if (c != null) {
                var spanId = c.id;
                if (c.id.substring(0, 7) == "content") f = c;
                else if (c.id.substring(0, 4) == "span") {
                    b = c;
                    for (var a = 0; a < c.childNodes.length; a++) if (c.childNodes[a].id.substring(0, 7) == "content") {
                        f = c.childNodes[a];
                        break
                    }
                }
                if (f == null) return;
                k.selectAllChildren(f);
                b = f.parentNode;
                g_oSelRw = b;
                g_oSelSpan = b;
                for (var a = 0; a < b.childNodes.length; a++) if (b.childNodes[a].id == "divEntityData") {
                    i = b.childNodes[a];
                    break
                }
                if (i != null) {
                    var o = i.getAttribute("isresolved");
                    if (o == "False") {
                        var h = b;
                        if (h.getBoundingClientRect().right > h.parentNode.getBoundingClientRect().right) h = h.parentNode;
                        var d = b.parentNode.id.replace("_upLevelDiv", ""),
							j = i.getAttribute("key"),
                            displayText = bus_Trim(i.getAttribute("displaytext")),
							e = DeferCall("CMenu", "Entity_Menu" + g_menuCounter);
                        g_menuCounter++;
                        var accountList = j;
                        var accounts = accountList.split(';');
                        var g = null;
                        //if (matches[d] != null && matches[d][j] != null) g = matches[d][j];
                        var l = document.getElementById(d),
							m = l.getAttribute("MoreItemsText"),
							q = l.getAttribute("RemoveText"),
							n = l.getAttribute("NoMatchesText");
                        if (accounts == null || accounts.length == 0) CAMOpt(e, n, "InfoBus_EENoMatchFound('" + STSScriptEncode(d) + "');");
                        else for (var a = 0; a < accounts.length; a++) {

                            var p = accounts[a];
                            //var t = accounts[l];
                            if (p != "")
                                CAMOpt(e, p, "InfoBus_EEReplace('" + STSScriptEncode(d) + "', '" + p.replace("\\", "\\\\") + "', " + a + ",'" + displayText + "');")
                            //CAMOpt(e, p.getAttribute("DisplayText"), "InfoBus_EEReplace('" + STSScriptEncode(d) + "', '" + STSScriptEncode(j) + "', " + a + ");")
                        }
                        CAMSep(e);
                        CAMOpt(e, q, "InfoBus_EERemove('" + STSScriptEncode(d) + "','" + displayText + "');");
                        CAMOpt(e, m, "InfoBus_EEShowMore('" + STSScriptEncode(d) + "', '" + STSScriptEncode(displayText) + "');");
                        OMenu(e, h, null, null, -1);
                        stopBubble(r)
                    }
                }
            }
        }
    }
}

function InfoBus_ClickRwIE(bool1, bool2, event, control) {
    var a = document.selection.createRange(),
		c = null,
		b = null;

    if (typeof a.parentElement == "function" || typeof a.parentElement == "object") c = a.parentElement();
    else {
        var v = a.item(0);
        c = v
    }
    var spanId = c.id;
    var displayText = "";
    if (c.tagName == "SPAN" && spanId.split(',')[0] == "content") b = c.parentElement;
    else if (c.tagName == "SPAN" && c.id.substring(0, 4) == "span" && !s) b = c;
    if (b != null) {
        var divEdId = "divEntityData";
        if (spanId.split(',').length > 1)
            divEdId = divEdId + "," + spanId.split(',')[1];
        var o = b.children(divEdId);
        var p = o.getAttribute("isresolved");
        a.moveToElementText(b);
        var n = "character";
        a.moveStart(n, -1);
        if (p == "False" && typeof _fV4UI != "undefined" && _fV4UI) {
            a.select();
            a.moveEnd(n, 1)
        } else {
            a.moveEnd(n, 1);
            a.select()
        }
        g_oSelRw = a;
        if (browseris.ie8standard) {
            b.contentEditable = false;
            g_oSelSpan = b
        }
        if (p == "False") {
            var h = b;
            if (h.getBoundingClientRect().right > h.parentElement.getBoundingClientRect().right) h = h.parentElement;
            var d = b.parentElement.id.replace("_upLevelDiv", ""),
				j = o.getAttribute("key"),
                displayText = bus_Trim(o.getAttribute("displaytext"));
            f = DeferCall("CMenu", "Entity_Menu" + g_menuCounter);
            g_menuCounter++;
            var accountList = j;
            var accounts = accountList.split(';');
            var g = null;
            //if (matches[d] != null && matches[d][j] != null) g = matches[d][j];
            var m = document.getElementById(d),
				q = m.getAttribute("MoreItemsText"),
				u = m.getAttribute("RemoveText"),
				r = m.getAttribute("NoMatchesText");
            if (accountList == "" || accounts.length <= 0) CAMOpt(f, r, "InfoBus_EENoMatchFound('" + STSScriptEncode(d) + "');");
            else for (var l = 0; l < accounts.length; l++) {
                var t = accounts[l];
                if (t != "") {
                    CAMOpt(f, t, "InfoBus_EEReplace('" + STSScriptEncode(d) + "', '" + t.replace("\\", "\\\\") + "', " + l + ",'" + displayText + "');");
                }
            }
            CAMSep(f);
            CAMOpt(f, u, "InfoBus_EERemove('" + STSScriptEncode(d) + "','" + displayText + "');");
            CAMOpt(f, q, "InfoBus_EEShowMore('" + STSScriptEncode(d) + "', '" + STSScriptEncode(displayText) + "');");
            g_MenuEndOfDOM = false;
            _fV4UI = false;
            if (kfnDisableEvent == undefined)
                kfnDisableEvent = new Function("return false");
            OMenu(f, h, null, null, -1);
            $('.ms-MenuUIPopupBody tr').each(function () {
                var test = $(this)[0].outerHTML.replace("onmenuclick", "onclick");
                $(this).replaceWith(test);
            });
            g_MenuEndOfDOM = false;
            _fV4UI = false;
        } else if (browseris.ie8standard) b.contentEditable = false
    } else if (browseris.ie8standard) {
        var e = c;
        while (e != null && (e.id == null || e.id.indexOf(g_EntityEditorUpLevelId) == -1)) e = e.parentNode;
        if (e != null) for (var k = e.childNodes, i = 0; i < k.length; i++) if (k[i].tagName != null && k[i].tagName == "SPAN") k[i].contentEditable = true
    }
}

function InfoBus_EEShowMore(b, a) {
    __Dialog__InfoBusUserField(null, document.getElementById(b + "_Browse"), a); return false;
}
function InfoBus_EEReplace(a, b, c, displayText) {
    var a = a + "_upLevelDiv";
    var upLevel = document.getElementById(a);
    var updiv = $(upLevel);
    upLevel.innerHTML = updiv.text().replace(displayText, b);
    InfoBus_GetUpdatePrincipalsXml(upLevel);
}
function InfoBus_EERemove(a, displayText) {
    var a = a + "_upLevelDiv";
    var upLevel = document.getElementById(a);
    var updiv = $(upLevel); 
    upLevel.innerHTML = updiv.text().replace(displayText, "");
    InfoBus_GetUpdatePrincipalsXml(upLevel);
}

function InfoJetCustom_OpenNewForm(publishUrl, isCurrentTemplate) {
}

function InfoBus_CustomGetIFrameContext() {
    var context = {};
    return context;
}

function InfoBus_CustomTry2CloseWindow(isPromptToSaveChanges) {
    if (isPromptToSaveChanges) {
        var formFrame = window.frames["container"];
        var formWindow = formFrame.window;
        if (formFrame.window) {
            formWindow = formFrame.window;
        } else if (formFrame.contentWindow) {
            formWindow = formFrame.contentWindow;
        }
        if (formWindow.InfoJet_Changed) {
            if (window.confirm('The data on this form might have changed. Are you sure you want to close this form?')) {
                closeWin(window);
            }
        } else {
            closeWin(window);
        }
    } else {
        closeWin(window);
    }
}